package com.单例模式;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

// 懒汉式单例
// 道高一尺，魔高一丈
public class LazyMan {

    private static boolean qingjiang = false;

    private LazyMan() {
        synchronized (LazyMan.class) {
            if (qingjiang = false) {
                qingjiang = true;
            }
            if (lazyMan != null) {
                throw new RuntimeException("不要试图使用反射破坏异常");
            }
        }
    }

    private volatile static LazyMan lazyMan;

    // 双重检测锁模式：懒汉式单例（DCL懒汉式）
    public static LazyMan getInstance() {
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan(); // 不是一个原子性操作
                    /**
                     * 1.分配内存空间
                     * 2.执行构造方法，初始化对象
                     * 3.把这个对象指向这个空间
                     *
                     * */
                }
            }
        }
        return lazyMan;
    }

    // 反射
    public static void main(String[] args) throws Exception {
//        LazyMan lazyMan1 = LazyMan.getInstance();
        Field qingjiang = LazyMan.class.getDeclaredField("qingjiang");
        qingjiang.setAccessible(true);
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);// 无视私有构造器
        LazyMan lazyMan1 = declaredConstructor.newInstance();
        qingjiang.set(lazyMan1, false);
        LazyMan lazyMan2 = declaredConstructor.newInstance();

        System.out.println(lazyMan1);
        System.out.println(lazyMan2);

    }

    // 多线程并发
//    public static void main(String[] args) {
//        for (int i = 1; i <= 10; i++) {
//            new Thread(() -> {
//                LazyMan.getInstance();
//            }, String.valueOf(i)).start();
//        }
//    }

}
